import React, {Component} from 'react';

import store from './store';
import {
    getInputChangeAction,
    getAddItemAction,
    getItemDeleteAction,
    getInitList
} from './store/actionCreators';

import TodoListView from './TodoListView';


class TodoList extends Component{

    constructor(props){
        super(props);
        this.state = store.getState();
        this.handleInputChange = this.handleInputChange.bind(this); //? 对this作用域做一个绑定
        this.handleStoreChange = this.handleStoreChange.bind(this); //?
        this.handleButtonClick = this.handleButtonClick.bind(this); //?
        this.handleItemDelete = this.handleItemDelete.bind(this);
        store.subscribe(this.handleStoreChange)
    }

    render() {
        return (
            <TodoListView
                inputValue={this.state.inputValue}
                list={this.state.list}
                handleInputChange={this.handleInputChange}
                handleButtonClick={this.handleButtonClick}
                handleItemDelete={this.handleItemDelete}
            />
        )
    }

    componentDidMount() {
        const action = getInitList();
        store.dispatch(action);
    }

    handleInputChange(e){
        const action = getInputChangeAction(e.target.value);
        store.dispatch(action); // 传递给store, store它不知道要干什么, 转发给reducer, reducer处理完再返回给store
    }

    handleStoreChange(){
        this.setState(store.getState());
    }

    handleButtonClick(){
        const action = getAddItemAction();
        store.dispatch(action); // 传递给store, store它不知道要干什么, 转发给reducer, reducer处理完再返回给store
    }

    handleItemDelete(index){
        const action = getItemDeleteAction(index);
        store.dispatch(action);
    }

}

export default TodoList;